<?php
declare (strict_types=1);

namespace app\admin\logic\site;

use app\admin\logic\system\Log;
use app\admin\model\site\Personal as PersonalModel;
use app\admin\model\site\PersonalData;
use app\common\exception\LogicException;
use think\Collection;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Raw;

/**
 * @method leftJoin(string $string, string $joinOn)
 */
class Personal extends PersonalModel
{

    /**
     * 获取列表
     * Author: Martinsun <syh@sunyonghong.com>
     * Date: 2021/10/21
     *
     * @param $type
     * @return array
     * @throws DbException
     */
    public function getList($type)
    {
        $arr    = ['app' => 1, 'wap' => 0];
        $device = $arr[$type];
        $joinOn = ' `a`.`id` = `d`.`config_id`';
        $joinOn .= ' AND `d`.`mhm_id` = ' . request()->mhm_id;
        $joinOn .= ' AND `d`.`data_type` = 2';

        $order = new Raw('d.sort is null,d.sort ASC,a.sort ASC,d.update_time DESC,a.id ASC');

        if ($type !== 'wap') {
            $where = [];
            if (!request()->is_platform) {
                $where[] = ['a.key', '<>', 'school'];
            }
            $items = $this->with(['personalData'])->alias('a')
                ->leftJoin('site_personal_data d', $joinOn)
                ->where('a.device_type', $device)
                ->where($where)
                ->field('a.*')
                ->order($order)
                ->select();
            foreach ($items as $k => $item) {
                $item->icon_url = $item->iconUrl ? $item->iconUrl->fileurl : '';
                $personalData   = $item->personalData;
                $item['status'] = 1;
                $items[$k]      = $this->getItem($personalData, $item);
            }
            unset($item);

            return $items->hidden(['iconUrl', 'personalData']);
        }

        // 关联查询
        $items = $this->with(['group_base', 'personal_data'])->alias('a')
            ->leftJoin('site_personal_data d', $joinOn)
            ->where('a.device_type', $device)
            ->field('a.*')
            ->order($order)
            ->select();
        $datas = [];
        foreach ($items as $item) {
            $item->icon_url = $item->iconUrl ? $item->iconUrl->fileurl : '';
            if (!isset($datas[$item['group_id']])) {
                $groupData                = app(PersonalData::class)->where('data_type', 1)->where('config_id', $item['group_id'])->where('mhm_id', request()->mhm_id)->findOrEmpty();
                $datas[$item['group_id']] = [
                    'title'    => $groupData->getAttr('title') ?: $item['group_title'],
                    'sort'     => $groupData->getAttr('sort') ?: $item['group_sort'],
                    'id'       => 'g_' . $item['group_id'],
                    'gid'      => $item['group_id'],
                    'children' => []
                ];
            }
            $item['hasChildren'] = false;
            $item['status']      = 1;
            $personalData        = $item->personalData;
            $item                = $this->getItem($personalData, $item);

            $datas[$item['group_id']]['children'][] = $item->hidden(['iconUrl', 'personalData'])->toArray();
        }
        foreach ($datas as &$data) {
            $data['status'] = intval(in_array(1, array_column($data['children'], 'status')));
        }

        $datas = Collection::make($datas)->order('sort')->toArray();

        return array_values($datas);

    }

    public function editItem($id, $param)
    {
        // 验证数据
        // $this->getValidate()->scene('edit')->failException()->check($check);
        //
        $item = $this->findOrFail($id);
        //
        // $item->title = $param['title'];
        // $item->icon  = $param['icon'];
        // $item->group_id = $param['group_id'];
        // $item->status   = $param['status'] ?? 1;

        // 更改数据表
        $personalData = app(PersonalData::class)->where('data_type', 2)->where('config_id', $id)->where('mhm_id', request()->mhm_id)->findOrEmpty();

        if ($personalData->isEmpty()) {
            $personalData->icon   = $item['icon'];
            $personalData->title  = $item['title'];
            $personalData->status = 1;
            $personalData->sort   = 1;
        }
        $personalData->config_id = $id;
        if ($param['title']) {
            $personalData->title = $param['title'];
        }
        if (isset($param['status'])) {
            $personalData->status = intval($param['status']);
        }
        if ($param['sort']) {
            $personalData->sort = $param['sort'];
        }

        if ($param['icon']) {
            $personalData->icon = $param['icon'];
        }

        if (!$personalData->force()->save()) {
            throw new LogicException("编辑失败");
        }

        // 更新成功
        Log::write('更新个人中心菜单【' . $param['title'] . '】', 'site_personal', 'update', true);

        // Db::name('test')->save(['msg'=>'更新个人中心菜单']);
        return $item;
    }

    public function editItemField($id, $field, $param)
    {
        $item = $this->findOrFail($id);
        // 更改数据表
        $personalData = app(PersonalData::class)->where('data_type', 2)
            ->where('config_id', $id)
            ->where('mhm_id', request()->mhm_id)
            ->findOrEmpty();
        if ($personalData->isEmpty()) {
            $personalData->icon      = $item['icon'];
            $personalData->config_id = $item['id'];
            $personalData->title     = $item['title'];
            $personalData->status    = 1;
            $personalData->sort      = 1;
        }
        $personalData->$field = $param[$field];
        if (!$personalData->force()->save()) {
            throw new LogicException("修改失败");
        }

        // 更新成功
        Log::write('更新个人中心菜单【' . $item->getAttr('title') . '】', 'site_personal', 'update', true);

        return $item;
    }

    /**
     * 更新组所有菜单状态
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 22/02/08
     *
     * @param int $gid
     * @param     $param
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function updateStatusByGroupId(int $gid, $param)
    {
        // $re = Db::name('site_personal_config')->where('group_id', $gid)->update($param);

        // 获取分组下所有菜单
        $items = $this->where('group_id', $gid)->select();
        $count = 0;
        foreach ($items as $item) {
            // 更改数据表
            $personalData = app(PersonalData::class)->where('data_type', 2)
                ->where('config_id', $item['id'])
                ->where('mhm_id', request()->mhm_id)
                ->findOrEmpty();
            if ($personalData->isEmpty()) {
                $personalData->icon      = $item['icon'];
                $personalData->config_id = $item['id'];
                $personalData->title     = $item['title'];
                $personalData->sort      = 1;
            }
            $personalData->status = $param['status'];
            if ($personalData->save()) {
                $count++;
            }

        }
        if ($count === 0) {
            throw new LogicException("更新状态失败");
        }
        $group = app(PersonalGroup::class)->findOrEmpty($gid);
        // 更新成功
        Log::write('更新个人中心菜单【' . $group->getAttr('title') . '】状态', 'site_personal', 'update', true);
    }

    /**
     * getItem
     * Author: 亓官雨树 <lucky.max@foxmail.com>
     * Date: 23/07/19
     *
     * @param $personalData
     * @param $item
     * @return mixed
     */
    protected function getItem($personalData, $item)
    {
        if ($personalData) {
            $item['icon_url'] = $personalData->icon ? $personalData->icon_url : $item->icon_url;
            $item['title']    = $personalData->title ?: $item['title'];
            $item['status']   = $personalData->status ?: 0;
            $item['sort']     = $personalData->sort ?: $item['sort'];
        }

        return $item;
    }
}
